package td.pt.widget;

import java.util.ArrayList;

import td.domain.TagThought;
import td.domain.Thought;
import td.pt.event.ViewTagsOnThoughtEvent;
import td.pt.event.ViewTagsOnThoughtEvent.ViewTagsOnThoughtHandler;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.ListDataProvider;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.PopupView;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.proxy.RevealRootPopupContentEvent;

public class TagListingPopupPresenter extends
		PresenterWidget<TagListingPopupPresenter.MyView> {

	public interface MyView extends PopupView {
		public void refresh();

		public Label getTitle();

		Button getClose();

		CellTable<TagThought> getCellTable();

		ListDataProvider<TagThought> getDataProvider();
	}

	ViewTagsOnThoughtHandler viewTagsOnThoughtHandler = new ViewTagsOnThoughtHandler() {

		@Override
		public void onViewTagsOnThought(ViewTagsOnThoughtEvent event) {
			getView().getTitle().setText(
					"Tags for '" + event.getThought().getTitle() + "' Thought");
			refresh(event.getThought());
			RevealRootPopupContentEvent.fire(event.getSource(),
					TagListingPopupPresenter.this);
		}
	};

	@Inject
	public TagListingPopupPresenter(final EventBus eventBus, final MyView view) {
		super(eventBus, view);
	}

	@Override
	protected void onBind() {
		super.onBind();
		registerHandler(getEventBus().addHandler(ViewTagsOnThoughtEvent.TYPE,
				viewTagsOnThoughtHandler));
		getView().getClose().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				getView().hide();
			}
		});
	}

	@Override
	protected void onReveal() {
		super.onReveal();
	}

	private void refresh(Thought thought) {
		ArrayList<TagThought> tags = new ArrayList<TagThought>(thought
				.getAppliedTags().values());
		getView().getCellTable().setRowData(tags);
		getView().getCellTable().setPageSize(12);
		getView().getDataProvider().getList().clear();
		getView().getDataProvider().getList().addAll(tags);
		getView().refresh();
	}
}
